package com.tticar.invmanager.controller;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.czy.tticar.dubbo.dto.GoodsDetailCfgResponse;
import com.czy.tticar.dubbo.dto.StorageOrderConfirmResponse;
import com.czy.tticar.dubbo.dto.StorageOrderSaveRequest;
import com.czy.tticar.dubbo.service.StorageStoreService;
import com.tticar.invmanager.common.shiro.MySecurityUtils;
import com.tticar.invmanager.common.utils.MyResponseBody;
import com.tticar.invmanager.entity.SysTenant;
import com.tticar.invmanager.entity.vo.KwTree;
import com.tticar.invmanager.entity.vo.MyPage;
import com.tticar.invmanager.entity.vo.PlaceOrderDTO;
import com.tticar.invmanager.entity.vo.RelativeGoodsDTO;
import com.tticar.invmanager.mapper.MMaterielSkuMapper;
import com.tticar.invmanager.service.IMMaterielTticarService;
import com.tticar.invmanager.service.ISysTenantService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.tticar.invmanager.entity.MMaterielTticar;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 天天爱车产品 前端控制器
 * </p>
 *
 * @author joeyYan
 * @since 2018-07-23
 */
@Controller
@RequestMapping("/mMaterielTticar")
public class MMaterielTticarController extends BaseController {

    @Autowired
    private IMMaterielTticarService mMaterielTticarService;
    @Autowired
    private StorageStoreService storageStoreService;
    @Autowired
    private ISysTenantService sysTenantService;
    @Autowired
    private MMaterielSkuMapper mMaterielSkuMapper;

    @PostMapping("deleteRelative")
    @ResponseBody
    public MyResponseBody deleteRelative(String goodsId) {
        mMaterielSkuMapper.deleteRelative(goodsId);
        return MyResponseBody.success();
    }

    @PostMapping
    @ResponseBody
    public MyResponseBody post(MMaterielTticar mMaterielTticar) {
        mMaterielTticarService.insertOrUpdate(mMaterielTticar);
        return MyResponseBody.success();
    }

    @PostMapping("delete")
    @ResponseBody
    public MyResponseBody delete(@RequestParam("ids[]") List<Long> ids) {
        MyResponseBody responseBody = MyResponseBody.success();
        mMaterielTticarService.delete(ids);
        return responseBody;
    }

    @GetMapping("edit")
    public String edit(MMaterielTticar mMaterielTticar, ModelMap modelMap) {
        modelMap.put("id", mMaterielTticar.getId());
        return "/mMaterielTticar/mMaterielTticar_edit";
    }

    @GetMapping("list")
    @ResponseBody
    public Page list(MMaterielTticar mMaterielTticar, MyPage<MMaterielTticar> page) {
        Map param = getParam();
        return mMaterielTticarService.selectPage(mMaterielTticar, param, page);
    }

    @GetMapping
    public String index() {
        return "/tticar/mMaterielTticar/mMaterielTticar";
    }

    @RequestMapping("relativeGoods")
    @ResponseBody
    public List<RelativeGoodsDTO> treeGrid(Long tticarGoodsId,String skuValue) {
        if (tticarGoodsId == null || StringUtils.isBlank(skuValue)) {
            return null;
        }
        List<RelativeGoodsDTO> relativeGoodsDTOs = mMaterielTticarService.queryRelativeGoodsByTticarGoods(tticarGoodsId, skuValue);
        if (relativeGoodsDTOs != null && relativeGoodsDTOs.size() > 0) {
            for (RelativeGoodsDTO dto : relativeGoodsDTOs) {
                dto.setTticarGoodsId(tticarGoodsId.toString());
                dto.setSkuValue(skuValue);
            }
        }
        return relativeGoodsDTOs;
    }

    @RequestMapping("queryRelativeGoodsForPlaceOrder")
    @ResponseBody
    public List<List<RelativeGoodsDTO>> queryRelativeGoodsForPlaceOrder(@RequestParam("tticarGoodsId")Long tticarGoodsId,@RequestParam("skuValue")String skuValue,@RequestParam("customId") Long customId,
                                                                  @RequestParam("rows")String rows,@RequestParam("addrId")Long addrId,
                                                                  @RequestParam("sellStoreId")Long sellStoreId) {

        if (tticarGoodsId == null || StringUtils.isBlank(skuValue)) {
            return null;
        }
        List<List<RelativeGoodsDTO>> listReturn =new ArrayList<List<RelativeGoodsDTO>>();
        List<PlaceOrderDTO> placeOrderDTOs = JSONArray.parseArray(rows, PlaceOrderDTO.class);
        for (int i = 0; i<placeOrderDTOs.size();i++) {

            if (StringUtils.isBlank(placeOrderDTOs.get(i).getId())) {
                break;
            }


            //仓储本地关联的存货信息
            List<RelativeGoodsDTO> relativeGoodsDTOs = new ArrayList<>();
            relativeGoodsDTOs = mMaterielTticarService.queryRelativeGoodsByTticarGoods(Long.valueOf(placeOrderDTOs.get(i).getId().split(",")[0]), placeOrderDTOs.get(i).getId().split(",")[1]);
            if (relativeGoodsDTOs == null || relativeGoodsDTOs.size() < 1) {
                RelativeGoodsDTO dto = new RelativeGoodsDTO();
                dto.setRepositoryCount(0);
                dto.setName("无");
                dto.setSkuName("");
                relativeGoodsDTOs.add(dto);
            }


            //查询天天爱车的商品单价和运费
            GoodsDetailCfgResponse goodsDetailCfgResponse = storageStoreService.goodsDetailCfg(Long.valueOf(placeOrderDTOs.get(i).getId().split(",")[0]), placeOrderDTOs.get(i).getId().split(",")[1], customId);

            //start
            //查询优惠价格
            List<PlaceOrderDTO> placeOrderDTOs1 = JSONArray.parseArray(rows, PlaceOrderDTO.class);
            List<StorageOrderSaveRequest.GoodsOrder> goodsOrderDtos = new ArrayList<>();
            StorageOrderSaveRequest.GoodsOrder goodsOrder = new StorageOrderSaveRequest.GoodsOrder();
            List<StorageOrderSaveRequest.GoodsOrderGoods> goodsOrderGoodsList = new ArrayList<>();
            for (PlaceOrderDTO placeOrder : placeOrderDTOs1) {
                if (StringUtils.isBlank(placeOrder.getId())) {
                    break;
                }
                StorageOrderSaveRequest.GoodsOrderGoods goodsOrderGoods = new StorageOrderSaveRequest.GoodsOrderGoods();
                goodsOrderGoods.setGoodsId(Long.valueOf(placeOrder.getId().split(",")[0]));
                goodsOrderGoods.setSkuId(placeOrder.getId().split(",")[1]);
                goodsOrderGoods.setCount(Long.valueOf(placeOrder.getCount()));
//                if (placeOrder.getUnitPrice()!=null && placeOrder.getUnitPrice().compareTo(BigDecimal.ZERO) > 0) {
//                    goodsOrderGoods.setPrice(placeOrder.getUnitPrice());
//                }

                goodsOrderGoodsList.add(goodsOrderGoods);
            }
            goodsOrder.setGoodsOrderGoodsDtos(goodsOrderGoodsList);
            goodsOrderDtos.add(goodsOrder);

            StorageOrderSaveRequest requestDto = new StorageOrderSaveRequest();
            requestDto.setGoodsOrderDtos(goodsOrderDtos);

            requestDto.setStoreId(customId);
            requestDto.setSellStoreId(sellStoreId);
            requestDto.setAddrId(addrId);
            requestDto.setOptId(MySecurityUtils.currentUser().getId());
            requestDto.setOptName(MySecurityUtils.currentUser().getNickname());


            StorageOrderConfirmResponse storageOrderConfirmResponse = storageStoreService.storageConfirmOrder(requestDto);

            BigDecimal totalDiscount = storageOrderConfirmResponse.getGoodsOrderDtos().get(0).getTotalDiscount();
            //end

            /**
             * 如果该租户不需要关联仓储存货，直接跳出
             * */
            Wrapper wrapper = new EntityWrapper<>();
            wrapper.eq("need_relative_inv", 1);
            List<SysTenant> sysTenants = sysTenantService.selectList(wrapper);
            Integer needInv = 0;
            for (SysTenant sys : sysTenants) {
                if (sys.getId().equals(MySecurityUtils.currentUser().getTenantId())) {
                    needInv = 1;
                }
            }
            if (relativeGoodsDTOs != null && relativeGoodsDTOs.size() > 0) {
                for (RelativeGoodsDTO dto : relativeGoodsDTOs) {
                    if (StringUtils.isNotBlank(dto.getSkuName())) {
                        dto.setName(dto.getName() + "  " + dto.getSkuName());
                    }
                    //单价
                    dto.setUnitPrice(goodsDetailCfgResponse.getpValue());
                    //总价
                    dto.setAllMoney(storageOrderConfirmResponse.getAllMoney());
                    //优惠
                    dto.setDiscoutFee(totalDiscount);

                    dto.setNeedInv(needInv);
                }
            }
            listReturn.add(relativeGoodsDTOs);
    }

        return listReturn;
    }

    @RequestMapping("cancelRelative")
    @ResponseBody
    public MyResponseBody  cancelRelative(Long skuId,String tticarGoodsId,String skuValue) {
        MyResponseBody responseBody = MyResponseBody.success();
        mMaterielTticarService.cancelRelative(skuId,tticarGoodsId,skuValue);
        return responseBody;
    }

}
